import dotenv from "dotenv";
dotenv.config();
import { Database } from "./database.js";
import { MySql } from "./mysql.js";
import { Sqlite } from "./sqlite.js";

/**
 * 创建数据库连接实例
 *
 * @param {string} config 数据库连接字符串：mysql://localhost:3306
 * @returns {Promise<Database>}
 */
export function createDatabase(config) {
  const { DATABASE_URL = config } = process.env;
  const [schema, uri] = DATABASE_URL.split("://");
  if (["sqlite", "sqlite3"].includes(schema)) {
    // const { Sqlite } = await import("./sqlite.js");
    return new Sqlite(uri);
  } else if (schema === "mysql") {
    // const { MySql } = await import("./mysql.js");
    return new MySql(DATABASE_URL);
  }
  console.log(`Unsupported database schema: ${schema}`);
  process.exit(1);
}

// 生产全局连接对象
export const db = createDatabase();
export default db;
